<template>
  <div class="form-container">
    <Form :model="model" ref="formRef">
      <Row :gutter="24">
        <Col v-for="(schema, index) in list" :key="schema.field" :span="col">
          <FormItem
            :label="schema.label"
            :name="schema.field"
            :rules="schema.rules"
            v-show="showItem(schema.show)"
            :labelCol="{ span: 4 }"
          >
            <template v-if="schema.type === 'Slot'">
              <slot name="slot" />
            </template>
            <template v-else-if="schema.type === 'Render' && schema.render">
              <component :is="schema.render()" />
            </template>
            <template v-else>
              <component
                :is="controlMap[schema.type]"
                v-model="model[schema.field]"
                v-bind="schema.props"
              />
            </template>
          </FormItem>
        </Col>
      </Row>
    </Form>
  </div>
</template>

<script setup lang="ts">
import type { FormInstance } from 'ant-design-vue';

import type { Filter, ControlMap } from '../types/comp';

import { ref, useTemplateRef } from 'vue';

import { Form, FormItem, Row, Col } from 'ant-design-vue';

import Input from './input.vue';

import Select from './select.vue';

import Password from './password.vue';

import Switch from './switch.vue';

import InputNumber from './number.vue';

import Upload from './upload.vue';

const props = withDefaults(defineProps<Filter>(), {
  col: 8,
  list: () => [],
});

const model = defineModel<any>();

const emits = defineEmits(['search']);

const controlMap: ControlMap = {
  Input,
  Select,
  Password,
  Switch,
  InputNumber,
  Upload,
};

const formRef = useTemplateRef<FormInstance>('formRef');

const handleReset = () => {
  formRef.value?.resetFields();
};

const handleSubmit = async () => {
  try {
    return await formRef.value?.validate();
    // emits('search');
  } catch (error) {
    console.log(error, 'error');
  }
};

function showItem(show: boolean | undefined) {
  if (typeof show === 'undefined') return true;
  return show;
}

defineExpose({
  handleReset,
  handleSubmit,
});
</script>

<style scoped>
.form-container {
  /* padding: 16px; */
  /* border: 1px solid #ddd; */
  /* border-radius: 4px; */
}
</style>
